﻿#include "delivery.h"
#include "ui_delivery.h"

#include <QDateTime>

Delivery::Delivery(QDialog *parent, QString select_id_tmp) :
    QDialog(parent),
    ui(new Ui::Delivery),
    select_id(select_id_tmp)
{
    ui->setupUi(this);
    setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);
    setFixedSize(this->width(),this->height());
    comboboxinit();//读取数据库商品编号到combo box
}

Delivery::~Delivery()
{
    delete ui;
}

void Delivery::on_outputButton_clicked()
{
    // 获取combo box控件里的值
    QString id = ui->idcomboBox->currentText();

    // 判断出库商品数量是否为空
    if(ui->amountlineEdit->text().isEmpty())
    {
        QMessageBox::information(this, "提示", "商品出库数量不能为空，请重试");
        ui->amountlineEdit->setFocus();
        return;
    }

    // 验证出库数量是否有效
    bool ok;
    int outputamount = ui->amountlineEdit->text().toInt(&ok);
    if (!ok || outputamount <= 0) {
        QMessageBox::information(this, "提示", "请输入有效的出库数量（必须为正整数）");
        ui->amountlineEdit->setFocus();
        ui->amountlineEdit->selectAll();
        return;
    }

    // 获取操作人
    QString operatorName = "系统管理员"; // 默认值
    // 如果有操作人输入框：QString operatorName = ui->operatorLineEdit->text();

    // 获取备注
    //QString remarks = ui->remarksTextEdit->toPlainText(); // 如果有备注输入框
    QString remarks;

    QSqlQuery sqlquery;

    // 开始事务
    QSqlDatabase::database().transaction();

    try {
        // 1. 查询商品当前信息
        QString strid = "StockId='";
        strid += id;
        strid += "'";

        QString str = QString("SELECT StockName, StockAmount, DeliveryTime FROM commoditydatatable WHERE %1").arg(strid);
        if (!sqlquery.exec(str)) {
            throw QString("查询商品信息失败: %1").arg(sqlquery.lastError().text());
        }

        QString strAmount;
        QString stockName;
        QString currentDeliveryTime;

        if (sqlquery.next()) {
            stockName = sqlquery.value(0).toString();  // 商品名称
            strAmount = sqlquery.value(1).toString();   // 库存数量
            currentDeliveryTime = sqlquery.value(2).toString(); // 当前出库时间
        } else {
            throw QString("未找到商品信息，商品可能不存在");
        }

        int tableamount = strAmount.toInt();
        int isum = tableamount - outputamount;

        // 检查库存是否足够
        if(isum < 0) {
            throw QString("库存不足！当前库存：%1，出库数量：%2").arg(tableamount).arg(outputamount);
        }

        QString strisum = QString::number(isum);

        // 获取当前时间作为出库时间
        QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");

        // 2. 更新商品库存和出库时间
        QString strdb = QString("UPDATE commoditydatatable SET StockAmount=%1, DeliveryTime='%2' WHERE %3")
                            .arg(strisum, currentTime, strid);

        if(!sqlquery.exec(strdb)) {
            throw QString("更新商品库存失败: %1").arg(sqlquery.lastError().text());
        }

        // 3. 添加出库操作记录
        if(!addStockOperationRecord("出库", id, stockName, outputamount, operatorName, remarks)) {
            throw QString("添加出库操作记录失败");
        }

        // 提交事务
        QSqlDatabase::database().commit();

        QMessageBox::information(this, "提示",
                                 QString("出库成功！\n\n"
                                         "商品：%1\n"
                                         "出库数量：%2\n"
                                         "原库存：%3\n"
                                         "现库存：%4\n"
                                         "出库时间：%5")
                                     .arg(stockName)
                                     .arg(outputamount)
                                     .arg(tableamount)
                                     .arg(isum)
                                     .arg(currentTime));

        // 清空输入框
        ui->amountlineEdit->clear();
        //ui->remarksTextEdit->clear();

        accept(); // 关闭对话框

    } catch (const QString &error) {
        // 回滚事务
        QSqlDatabase::database().rollback();
        QMessageBox::critical(this, "错误",
                              QString("出库失败！\n错误信息：%1").arg(error));
    }
}
void Delivery::on_exitButton_clicked()
{
    close();
}

//初始化combo box
void Delivery::comboboxinit()
{
    int i=0;
    QSqlQuery sqlQuery;
    sqlQuery.exec("select *from commoditydatatable");

    QString id;
    while(sqlQuery.next())
    {
        id=sqlQuery.value(0).toString();
        ui->idcomboBox->insertItem(i,id);
        i++;
    }
    ui->idcomboBox->setCurrentText(select_id);
}


// 添加库存操作记录
bool Delivery::addStockOperationRecord(const QString &operationType, const QString &stockId,
                                       const QString &stockName, int amount, const QString &operatorName,
                                       const QString &remarks)
{
    QSqlQuery query;

    // 准备SQL语句
    query.prepare("INSERT INTO stock_operations (operation_type, stock_id, stock_name, operation_amount, operator, operation_time, remarks) "
                  "VALUES (:operationType, :stockId, :stockName, :amount, :operator, :operationTime, :remarks)");

    // 绑定参数
    query.bindValue(":operationType", operationType);
    query.bindValue(":stockId", stockId);
    query.bindValue(":stockName", stockName);
    query.bindValue(":amount", amount);
    query.bindValue(":operator", operatorName);
    query.bindValue(":operationTime", QDateTime::currentDateTime());
    query.bindValue(":remarks", remarks);

    // 执行插入
    if(query.exec())
    {
        return true;
    }
    else
    {
        QMessageBox::warning(this, "警告",
                             QString("添加库存操作记录失败！错误信息：%1").arg(query.lastError().text()));
        return false;
    }
}
